package tag1;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class SimpleTag3 extends BodyTagSupport{
	private static final long serialVersionUID = 3964343505044946586L;
	
	@Override
	public int doEndTag() throws JspException {
		BodyContent body=getBodyContent();
		//格式化
		Gson gson = new Gson();
		List<HashMap<String, Object>> list = gson.fromJson(body.getString(), new TypeToken<List<HashMap<String, Object>>>(){}.getType());
		//构建html
		StringBuilder html = new StringBuilder();
		int len=list.size();
		StringBuilder[] tdHtmls=new StringBuilder[len];
		StringBuilder tdHtm=null;
		html.append("<table border=1><tr>");
		boolean isTH=true;
		for (int i=0;i<len;i++) {
			isTH=true;
			for (Entry<String, Object> en : list.get(i).entrySet()) {
				if(isTH){//获取所有th
					html.append("<th>").append(en.getKey()).append("</th>");
					isTH=false;
				}
				//构建th对应的所有td
				tdHtm=new StringBuilder();
				tdHtm.append("<td>").append(en.getValue()).append("</td>");
				tdHtmls[i]=tdHtm;
			}
		}
		html.append("</tr>")
			.append("<tr>");
		for(int i=0;i<len;i++){//将所有td片段构建到对应的th行下面
			html.append(tdHtmls[i]);
		}
		html.append("</tr></table>");
		
		//清理body中内容
		body.clearBody();
		//输出html内容
		JspWriter out = pageContext.getOut();
		try {
			out.println(html);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return super.doAfterBody();
	}
	
}
